import {
  Button,
  DatePicker,
  Divider,
  DotLoading,
  Form,
  Input,
  NavBar,
  Radio,
  Result,
  Space,
  Tag,
  TextArea,
  Toast,
} from 'antd-mobile';
import { RefObject, useEffect, useState } from 'react';

import type { DatePickerRef } from 'antd-mobile/es/components/date-picker';

import { Content, Page } from '@alita/flow';
import {
  setPageNavBar,
  useLocation,
  useNavigate,
  useSearchParams,
} from 'alita';

import { DemoBlock } from '@/components/demos-util';
import { DATE_FOMRAT } from '@/constants';
import { checkAuthorize } from '@/utils/authorize';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';

import { WeiXinUserPicker } from '@/pages/selectors/wei-xin-user';
import type { DetailResult } from '@/pages/types/type';

import { useModel } from 'alita';
import dayjs from 'dayjs';

// 生成的类型定义1个
declare type Standard = { label: string; value: string | number };

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(2);

  // 初始化类数据
  const [standards, setStandards] = useState<Standard[]>([]); // 角色/权限 可以选择的项，注解：interface annotations.ts.form.item.TsRadioFormItem

  // 生成的从地址中读取参数语句
  const origin: string = searchParams.get('origin')!; // 源对象
  const url: string = searchParams.get('url')!;

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  // 成功时返回控制
  const [livingId, setLivingId] = useState<number>();
  type FieldModal = {
    standard: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `添加角色/授权`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 1;
      // 加载角色/权限选项用于使用checkBox的选项值之中，注解：interface annotations.ts.form.item.TsRadioFormItem
      const standardOptionsUrl = `/api/${url}-type/standards`;
      let standardOptionsUrlResponse: Promise<Response> = fetch(
        `${urlPrefix}${standardOptionsUrl}`,
        getRequestInit(),
      );
      standardOptionsUrlResponse
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(async ({ data, code, msg }: DetailResult<Standard[]>) => {
                if (code === 0) {
                  setLoadOK(msg);
                  setStandards(data!);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              })
              .finally(() => {
                console.log(`${standardOptionsUrl} inner finally!`);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([
            ...loadFails,
            `请求${standardOptionsUrl}时发生错误：${reason}`,
          ]);
        })
        .finally(() => {
          console.log(`${standardOptionsUrl} outter finally!`);
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK, url]);

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // })
    const requestInit: RequestInit = postRequestInit({ origin, ...values });
    let response: Promise<Response> = fetch(
      `${urlPrefix}/api/${url}/creat-object-staff-living`,
      requestInit,
    );
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<number>) => {
              const { data: livingId, code, msg } = x;
              console.log('newlivingId  =', livingId);
              if (code === 0) {
                setSuccess(msg);
                Toast.show({ icon: 'success', content: '成功' });
                setLivingId(livingId);
              } else {
                setFail(msg);
                Toast.show({ icon: 'fail', content: msg });
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入{loadingTimes}次...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            添加角色或授权
          </NavBar>
        </DemoBlock>
        <DemoBlock padding={8}>
          <Form
            form={form}
            layout={'vertical'}
            onFinish={onFinish}
            footer={
              <>
                {success !== undefined && (
                  <Space direction="vertical">
                    <Result
                      status="success"
                      title="添加系统权限"
                      description={'添加成功！'}
                    />
                    <Button
                      color="default"
                      size="small"
                      onClick={() => setSuccess(undefined)}
                    >
                      继续授权
                    </Button>
                  </Space>
                )}
                {fail !== undefined && (
                  <Result
                    status="error"
                    title="执行失败"
                    description={
                      <Space direction="vertical">
                        {fail}
                        <Divider aria-orientation={'vertical'} />
                        <Button
                          color="default"
                          size="small"
                          onClick={() => setFail(undefined)}
                        >
                          再试一次
                        </Button>
                      </Space>
                    }
                  />
                )}
                <Button
                  block
                  type="submit"
                  disabled={
                    !authOK ||
                    ing ||
                    fail !== undefined ||
                    success !== undefined
                  }
                  loading={ing}
                  color="primary"
                  size="large"
                >
                  {success !== undefined ? '已申请' : '提交'}
                </Button>
              </>
            }
          >
            {standards.length > 0 && (
              <Form.Item
                name="standard"
                label="角色/权限"
                rules={[{ required: true, message: '角色/权限' }]}
              >
                <Radio.Group>
                  <Space direction="vertical">
                    {standards
                      .filter(
                        ({ value }) =>
                          !(
                            value === 'OTHER' ||
                            value === 'alive' ||
                            value === 'terminated'
                          ),
                      )
                      .map((s) => (
                        <Radio key={s.value} value={s.value}>
                          {s.label}
                          {s.value === 'managerSystemLevelRole' && (
                            <Tag color={'primary'}>根权限</Tag>
                          )}
                        </Radio>
                      ))}
                  </Space>
                </Radio.Group>
              </Form.Item>
            )}

            <Form.Item
              name="remark"
              initialValue={'无'}
              label="说明"
              help="说明"
              rules={[{ required: true, message: '备注' }]}
            >
              <TextArea
                placeholder="说明"
                maxLength={250}
                autoSize={{ minRows: 2, maxRows: 5 }}
                rows={2}
                showCount
              />
            </Form.Item>
            <WeiXinUserPicker name="leader" label="员工" required />

            {/*java注解：interface annotations.ts.form.item.TsDatePickerFormItem 代码搜索：RFGV-2039-E01Y*/}
            <Form.Item
              name="start"
              label="生效日期"
              trigger="onConfirm"
              rules={[{ required: true, message: '生效日期' }]}
              onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                datePickerRef.current?.open();
              }}
            >
              <DatePicker precision={'day'}>
                {(value) =>
                  value ? dayjs(value).format(DATE_FOMRAT) : '请选择日期'
                }
              </DatePicker>
            </Form.Item>
            <Form.Subscribe to={['standard']}>
              {({ standard }) => {
                return standard === 'managerSystemLevelRole' ? (
                  <Form.Item
                    required
                    name="createAdminPassword"
                    label="微信永久授权码或钉钉Key"
                  >
                    <Input placeholder="请向系统开发者查询" />
                  </Form.Item>
                ) : (
                  <></>
                );
              }}
            </Form.Subscribe>
          </Form>
        </DemoBlock>
      </Content>
    </Page>
  );
};
